package com.android.clinic.app.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseFragment;
import com.android.clinic.app.entity.NoticeInfo;
import com.android.clinic.app.entity.UserInfo;
import com.android.clinic.app.glide.ImageLoaderUtils;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.doctor.DoctorAdvisoryActivity;
import com.android.clinic.app.ui.personal.AttentionListActivity;
import com.android.clinic.app.ui.personal.BindVipActivity;
import com.android.clinic.app.ui.personal.LoginActivity;
import com.android.clinic.app.ui.personal.PersonalActivity;
import com.android.clinic.app.ui.personal.RenewalFeeMemberActivity;
import com.android.clinic.app.ui.personal.WebViewActivity;
import com.android.clinic.app.ui.widget.AccordionTextView;
import com.android.clinic.app.ui.widget.UIAlertView;
import com.android.clinic.app.utils.AppManager;
import com.android.clinic.app.utils.Constants;
import com.android.clinic.app.utils.DateUtils;
import com.android.clinic.app.utils.DisplayUtil;
import com.android.clinic.app.utils.PermissionUtils;
import com.android.clinic.app.utils.PreferencesUtils;
import com.android.clinic.app.utils.Toasty;
import com.android.clinic.app.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.List;

/**
 * Created by cheng on 2018/1/26.
 */
public class MineFragment extends BaseFragment implements View.OnClickListener {

    private TextView tvLogin;

    private TextView tvNickName, tvAge;
    private ImageView ivHead, ivSex, ivSos;

    private LinearLayout layLoginOut, layUserInfo;
    private RelativeLayout layPerson;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        tvLogin = (TextView) findViewById(R.id.tv_login);

        tvNickName = (TextView) findViewById(R.id.tv_nick_name);
        tvAge = (TextView) findViewById(R.id.tv_age);
        ivSex = (ImageView) findViewById(R.id.iv_sex);
        ivHead = (ImageView) findViewById(R.id.iv_head);
        ivSos = (ImageView) findViewById(R.id.iv_sos);

        AccordionTextView tvMineInquiry = (AccordionTextView) findViewById(R.id.tv_mine_inquiry);
        AccordionTextView tvMineAttention = (AccordionTextView) findViewById(R.id.tv_mine_attention);
        AccordionTextView tvMineOrder = (AccordionTextView) findViewById(R.id.tv_mine_order);
        AccordionTextView tvMineRecord = (AccordionTextView) findViewById(R.id.tv_mine_record);
        AccordionTextView tvMineCustomerService = (AccordionTextView) findViewById(R.id.tv_mine_customer_service);
        AccordionTextView tvMineBindVip = (AccordionTextView) findViewById(R.id.tv_mine_bind_vip);
        AccordionTextView tvMineUserProtocol = (AccordionTextView) findViewById(R.id.tv_mine_user_protocol);
        AccordionTextView tvMineNurse = (AccordionTextView) findViewById(R.id.tv_mine_nurse);
        AccordionTextView tvMineHealthFile = (AccordionTextView) findViewById(R.id.tv_mine_health_file);
        AccordionTextView tvRenewalFee = (AccordionTextView) findViewById(R.id.tv_mine_renewal_fee);
        layLoginOut = (LinearLayout) findViewById(R.id.layout_login_out);
        layPerson = (RelativeLayout) findViewById(R.id.layout_personal);
        layUserInfo = (LinearLayout) findViewById(R.id.layout_user_info);

        tvLogin.setOnClickListener(this);
        tvMineInquiry.setOnClickListener(this);
        tvMineAttention.setOnClickListener(this);
        tvMineOrder.setOnClickListener(this);
        tvMineRecord.setOnClickListener(this);
        tvMineCustomerService.setOnClickListener(this);
        tvMineBindVip.setOnClickListener(this);
        tvMineNurse.setOnClickListener(this);
        tvMineUserProtocol.setOnClickListener(this);
        tvMineHealthFile.setOnClickListener(this);
        tvRenewalFee.setOnClickListener(this);
        layLoginOut.setOnClickListener(this);
        layPerson.setOnClickListener(this);
        ivSos.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != ClinicApplication.getUserInfo()) {
            tvLogin.setVisibility(View.GONE);
            layUserInfo.setVisibility(View.VISIBLE);
            layPerson.setEnabled(false);
            layLoginOut.setVisibility(View.VISIBLE);
            // 如果为true, 说明用户更新过用户信息了, 回到我的需要从新获取用户信息,否则显示第一次登录获取的用户.
            if (Constants.isUpdate) {
                getUserInfo(ClinicApplication.getUserInfo().getId());
            } else {
                ImageLoaderUtils.getInstance().loadHeadImage(
                        !Utils.isEmpty(ClinicApplication.getUserInfo().getImgUrl())
                                ? ClinicApplication.getUserInfo().getImgUrl() : R.drawable.icon_head_default,
                        ivHead, DisplayUtil.dip2px(60), DisplayUtil.dip2px(60));
                tvNickName.setText(!Utils.isEmpty(ClinicApplication.getUserInfo().getNickName()) ? ClinicApplication.getUserInfo().getNickName() : "无");
                tvAge.setText(ClinicApplication.getUserInfo().getAge() + "岁");
                ivSex.setImageResource("男".equals(ClinicApplication.getUserInfo().getGender())
                        ? R.drawable.icon_mine_male : R.drawable.icon_mine_female);
            }
            if (TextUtils.isEmpty(PreferencesUtils.getString(getActivity(), Constants.NOTICE_KEY))) {
                getNoticeList();
            }

        } else {
            tvLogin.setVisibility(View.VISIBLE);
            layLoginOut.setVisibility(View.GONE);
            ivSex.setVisibility(View.GONE);
            tvNickName.setText("");
            tvAge.setText("");
            ImageLoaderUtils.getInstance().loadHeadImage(R.drawable.icon_head_default,
                    ivHead, DisplayUtil.dip2px(60), DisplayUtil.dip2px(60));
        }
    }

    @Override
    protected void loadData() {
    }

    /**
     * 获取用户信息
     * @param userId
     */
    private void getUserInfo(String userId) {
        HttpClient.getHttpService().getUserInfo(userId)
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<UserInfo>() {
                    @Override
                    public void onSuccess(UserInfo userInfo) {
                        ClinicApplication.saveUserInfo(userInfo);
                        ImageLoaderUtils.getInstance().loadHeadImage(userInfo.getImgUrl(), ivHead,
                                DisplayUtil.dip2px(60), DisplayUtil.dip2px(60));
                        tvNickName.setText(userInfo.getNickName());
                        long date = PreferencesUtils.getLong(getContext(), "date");
                        int age = DateUtils.getAge(new Date(date));
                        tvAge.setText(age + "岁");
                        ivSex.setImageResource("男".equals(userInfo.getGender()) ? R.drawable.icon_mine_male : R.drawable.icon_mine_female);
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
    }

    /**
     * 获取消息列表
     */
    private void getNoticeList() {
        if (!TextUtils.isEmpty(ClinicApplication.getUserInfo().getId())) {
            HttpClient.getHttpService().getNoticeList(ClinicApplication.getUserInfo().getId(), 10, 1)
                    .compose(RxObservableUtils.applySchedulers())
                    .subscribe(new BaseObserver<String>() {
                        @Override
                        public void onSuccess(String s) {
                            try {
                                JSONObject jsonObject = new JSONObject(s);
                                List<NoticeInfo> noticeInfoList = JSON.parseArray(jsonObject.optJSONArray("result").toString(),
                                        NoticeInfo.class);
                                for (NoticeInfo noticeInfo : noticeInfoList) {
                                    if (noticeInfo.getType().equals("inquire_answer")) {
                                        PreferencesUtils.putString(getActivity(), Constants.NOTICE_KEY, noticeInfo.getInquireId());
                                        break;
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(String message) {
                        }
                    });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login:
                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;
            // 问诊单
            case R.id.tv_mine_inquiry:
                if (TextUtils.isEmpty(PreferencesUtils.getString(getActivity(),
                        Constants.NOTICE_KEY))){
                    Toasty.showShort(getActivity(), "您还没有问诊单，快去咨询专家吧!");
                } else {
                    Intent intent = new Intent(getActivity(), DoctorAdvisoryActivity.class);
                    intent.putExtra("inquireId", PreferencesUtils.getString(getActivity(),
                            Constants.NOTICE_KEY));
                    startActivity(intent);
                }
                break;
            // 续费
            case R.id.tv_mine_renewal_fee:
                startActivity(new Intent(getActivity(), RenewalFeeMemberActivity.class));
                break;
            // 我的医生
            case R.id.tv_mine_attention:
                startActivity(new Intent(getActivity(), AttentionListActivity.class));
                break;
            // 订单
            case R.id.tv_mine_order:
                Toasty.showShort(getActivity(), "暂无订单!");
                break;
            // 消费记录
            case R.id.tv_mine_record:

                break;
            // 联系客服
            case R.id.tv_mine_customer_service:
                PermissionUtils.applyCallPhone(getActivity(), new PermissionUtils.CallBack() {
                    @Override
                    public void onGuarantee() {
                        UIAlertView.callPhoneDialog(getActivity(), "管家电话", "4001883525");
                    }

                    @Override
                    public void onDeny() {

                    }
                });
                break;
            // 用户协议
            case R.id.tv_mine_user_protocol:
                startActivity(new Intent(getActivity(),
                        WebViewActivity.class).putExtra("path", Constants.PROTOCOL_URL));
                break;
            // 健康档案
            case R.id.tv_mine_health_file:
                startActivity(new Intent(getActivity(), PersonalActivity.class));
                break;
            // 绑定VIP
            case R.id.tv_mine_bind_vip:
                startActivity(new Intent(getActivity(), BindVipActivity.class));
                break;
            //SOS急救电话
            case R.id.iv_sos:
                PermissionUtils.applyCallPhone(getActivity(), new PermissionUtils.CallBack() {
                    @Override
                    public void onGuarantee() {
                        UIAlertView.callPhoneDialog(getActivity(), "SOS急救电话", "4001883525");
                    }

                    @Override
                    public void onDeny() {

                    }
                });
                break;
            // 理疗上门
            case R.id.tv_mine_nurse:
                PermissionUtils.applyCallPhone(getActivity(), new PermissionUtils.CallBack() {
                    @Override
                    public void onGuarantee() {
                        UIAlertView.callPhoneDialog(getActivity(), "理疗上门", "4001883525");
                    }

                    @Override
                    public void onDeny() {

                    }
                });
                break;
            // 登出
            case R.id.layout_login_out:
                UIAlertView.alertDialog(getActivity(), "提示",
                        "是否确认登出!", new UIAlertView.OnThemeDialogListener() {
                            @Override
                            public void OnDismissButton() {

                            }
                            @Override
                            public void OnSureButton() {
                                exit();
                            }
                        },"确定","取消");
                break;
            default:break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (TextUtils.isEmpty(PreferencesUtils.getString(getActivity(),
                    Constants.NOTICE_KEY))) {
                getNoticeList();
            }
        }
    }

    private void exit(){
        ClinicApplication.saveUserInfo(null);
        startActivity(new Intent(getActivity(), LoginActivity.class));
        AppManager.getAppManager().finishAllActivity();
    }
}
